/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package br.com.sales.hancadsa.client.presenter.behavior;

import br.com.sales.generics.client.request.HannaRequestCallback;
import br.com.sales.hancadsa.client.presenter.HanCadSAPresenter;
import br.com.sales.hancadsa.client.presenter.bean.ProductBean;
import br.com.sales.hancadsa.client.server.HanCadSAService;
import br.com.sales.hancadsa.client.view.widget.NewRequestDialog;
import com.google.gwt.core.client.JsonUtils;
import com.google.gwt.event.dom.client.BlurEvent;
import com.google.gwt.event.dom.client.BlurHandler;
import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.Response;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.user.client.Window;
import com.google.inject.Inject;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 *
 * @author v
 */
public class HanCadSABehavior {

    private boolean isEditing;
    @Inject
    private NewRequestDialog requestDialog;
    @Inject
    private HanCadSAService service;
    private static final Map<String, ProductBean> CACHED = new LinkedHashMap(3);

    @Inject
    public HanCadSABehavior() {
    }

    public void onChangeProduct(final HanCadSAPresenter.Display display) {

        display.getProductEdit().addBlurHandler(new BlurHandler() {

            @Override
            public void onBlur(BlurEvent event) {
                final String value = display.getProductEdit().getValue();
                if (!CACHED.containsKey(value)) {
                    if (value != null && !"".equals(value)) {
                        service.getDataProduct(Long.parseLong(value),
                                new HannaRequestCallback() {

                                    @Override
                                    public void onResponseReceived(Request request, Response response) {
                                        ProductBean bean = new ProductBean();
                                        JSONObject json = new JSONObject(JsonUtils.safeEval(response.getText()));
                                        bean.setPrice(json.get("PRICE").isNumber().doubleValue());
                                        bean.setCount(((Number) json.get("COUNT").isNumber().doubleValue()).intValue());
                                        bean.setMinStock(((Number) json.get("MIN").isNumber().doubleValue()).intValue());
                                        bean.setProduct(Long.parseLong(value));
                                        display.getCountEdit().setValue("1");
                                        display.getPriceEdit().setValue(bean.getPrice().toString());
                                        CACHED.put(value, bean);
                                    }
                                });
                    }
                } else {
                    ProductBean bean = CACHED.get(value);
                    display.getCountEdit().setValue("1");
                    display.getPriceEdit().setValue(bean.getPrice().toString());
                }
            }
        });
    }

    public void onChangeCount(final HanCadSAPresenter.Display display) {
        display.getCountEdit().addBlurHandler(new BlurHandler() {

            @Override
            public void onBlur(BlurEvent event) {
                display.getAddItem().setEnabled(true);
                ProductBean bean = CACHED.get(display.getProductEdit().getValue());
                int count = Integer.parseInt(display.getCountEdit().getValue());
                if ((count + verifer(display)) > bean.getCount()) {
                    Window.alert("Quantidade para o produto maior que o estoque(" + bean.getCount() + ")");
                    display.getCountEdit().setFocus(true);
                    display.getAddItem().setEnabled(false);
                    return;
                }
                if ((bean.getCount() - (verifer(display) + count)) <= bean.getMinStock()) {
                    requestDialog.show(display, bean);
                }

            }
        });
    }

    private int verifer(HanCadSAPresenter.Display view) {
        int returnInt = 0;
        if (!isEditing) {
            for (int row = 1; row < view.getItemsGrid().getRowCount(); row++) {
                int value = Integer.parseInt(view.getProductEdit().getValueMap().get(view.getItemsGrid().getText(row, 0)));
                if (Integer.parseInt(view.getProductEdit().getValue()) == value) {
                    returnInt = Integer.parseInt(view.getItemsGrid().getText(row, 2));
                }
            }
        }
        return returnInt;
    }

    public void adjusterCached(HanCadSAPresenter.Display view) {
        if (!isEditing) {
            for (int row = 1; row < view.getItemsGrid().getRowCount(); row++) {
                String product = view.getProductEdit().getValueMap().get(view.getItemsGrid().getText(row, 0));
                ProductBean bean = CACHED.get(product);
                bean.setCount(bean.getCount() - Integer.parseInt(view.getItemsGrid().getText(row, 2)));
                CACHED.put(product, bean);
            }
        }
    }

    public void setIsEditing(boolean isEditing) {
        this.isEditing = isEditing;
    }
}
